<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
include_once 'pay123/rest.client.class.php';
include_once 'pay123/common.class.php';

class Pay123 {

    public static function checkResult($order) {
        $transactionID = $_GET['transactionID'];
        $time = $_GET['time'];
        $status = $_GET['status'];
//        if ((int)$status!=1) {
//            return false;
//        }
        $ticket = $_GET['ticket'];
        $aConfig = array
            (
            'key' => 'UPBEATVNzNhcamUcmkjdYca',
        );

        $recalChecksum = md5($status . $time . $transactionID . $aConfig['key']);
        if ($recalChecksum != $ticket) {
            return false;
        }
        $aConfig = array
            (
            'merchantCode' => 'UPBEATVN',
            'url' => 'https://mi.123pay.vn/queryOrder1',
            'key' => 'UPBEATVNzNhcamUcmkjdYca',
            'passcode' => 'UPBEATVNmLocakJ434Hucanc',
        );
        $notifiedStatus = 0; //for example your system did not receive notify status from 123Pay yet
        if (!$notifiedStatus) {
            try {
                $aData = array
                    (
                    'mTransactionID' => $transactionID,
                    'merchantCode' => $aConfig['merchantCode'],
                    'clientIP' => '127.0.0.1', //current browser ip
                    'passcode' => $aConfig['passcode'],
                    'checksum' => '',
                );
                $result = Common::callRest($aConfig, $aData);
                if ($result['httpcode'] == 200) {
                    /* Retun data format
                      Array
                      (
                      [0] => 1
                      [1] => 123P1210020000507
                      [2] => 1
                      [3] => 100000
                      [4] => 100000
                      [5] => BANKNET
                      [6] =>
                      [7] => bc44083e998b5e24a922ffad04ea779a84bb2ee3
                      [httpcode] => 200
                      )
                     */
                    if ($result[0] == '1') {
                        echo 'Order info:<hr>';
                        echo 'mTransactionId:' . $transactionID . '<br>';
                        echo '123PayTransactionId: ' . $result[1] . '<br>';
                        echo 'Status: ' . $result[2] . '<br>';
                        echo 'Amount: ' . $result[3] . '<br>';
                        echo '<hr>';
                        if ($result[2] == '1') {//success
                            //Do success call service
                            return true;
                        } else {
                            echo 'Payment cancel';return false;
                        }
                    } else {
                        echo 'Call service queryOrder fail: Order is processing. Please waiting some munite and check your order history list';
                        return false;
                    }
                } else {
                    //do error call service.
                    echo 'Call service queryOrder fail: Order is processing. Please waiting some munite and check your order history list';
                    return false;
                }
            } catch (Exception $e) {
                //write log here to monitor your exception
                echo 'Call service queryOrder fail: Order is processing. Please waiting some munite and check your order history list';
                return false;
            }
        } else {
            echo 'Show checkout result base on notify status';
            return false;
        }
    }

    public static function callRest($order) {
        $mTransactionID = $order->ticket_order_number;
        $user = Users::model()->findByPk($order->user_id);
        $order->total_price=MyFunctionCustom::percentage_calculate($order->total_price,$order->percentage);
        $aConfig = array
            (
            'url' => 'https://mi.123pay.vn/createOrder1',
            'key' => 'UPBEATVNzNhcamUcmkjdYca',
            'passcode' => 'UPBEATVNmLocakJ434Hucanc',
            'description' => 'Payment for upbeat.vn',
            'cancelURL' => Yii::app()->createAbsoluteUrl('site/order'),
            'redirectURL' => Yii::app()->createAbsoluteUrl('site/order'),
            'errorURL' => Yii::app()->createAbsoluteUrl('site/order'),
        );
        $aData = array
            (
            'mTransactionID' => $mTransactionID.'_'.time(),
            'merchantCode' => 'UPBEATVN',
            'bankCode' => $order->payment_type==2?'123PCC':'123PAY',
            'totalAmount' => $order->total_price,
            'clientIP' => $_SERVER['REMOTE_ADDR'],
            'custName' => $user->username,
            'custAddress' => $order->payment_address,
            'custGender' => 'M',
            'custDOB' => date('d/m/Y', strtotime($order->booked_date)),
            'custPhone' => $order->phone,
            'custMail' => $user->email,
            'description' => 'Payment for upbeat.vn',
            'cancelURL' => Yii::app()->createAbsoluteUrl('site/order'),
            'redirectURL' => Yii::app()->createAbsoluteUrl('site/order'),
            'errorURL' => Yii::app()->createAbsoluteUrl('site/order'),
            'passcode' => 'UPBEATVNmLocakJ434Hucanc',
            'checksum' => '',
            'addInfo' => 'Ban đang thanh toán cho website upbeat.vn',
        );

        return Common::callRest($aConfig, $aData);
    }

    public static function getPayMent($order) {


        $result = null;
        $resultMessage = '';



        try {
            $result = self::callRest($order); //call 123Pay service
            if ($result['httpcode'] == 200) {
                //call service success do success flow
                if ($result[0] == '1') {//service return success
                    //re-create checksum
                    $rawReturnValue = '1' . $result[1] . $result[2];
                    if ($result[2]) {//check checksum
                        //call php header to redirect to input card page
                        $resultMessage .= $result[2];
                    } else {
                        //Call 123Pay service create order fail, return checksum is invalid
                        $resultMessage .= 'Return data is invalid<br>';
                    }
                } else {
                    //Call 123Pay service create order fail, please refer to API document to understand error code list
                    //$result[0]=error code, $result[1] = error description
                    $resultMessage .= $result[0] . ': ' . $result[1];
                }
            } else {
                //call service fail, do error flow
                $resultMessage .= 'Call 123Pay service fail. Please recheck your network connection<br>';
            }
        } catch (Exception $e) {
            $resultMessage .= '<pre>';
            $resultMessage .= $e->getMessage();
        }
        return $resultMessage;
    }

}
